﻿// 注释

using Admin.EcsWeb.Option;
using Admin.NET.Core;
using Admin.NET.Core.Service;
using Furion;
using Furion.FriendlyException;
using GeneralCommon.Interfaces;
using GeneralCommon.Models.SignalR;
using Microsoft.AspNetCore.SignalR;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Admin.EcsWeb.Service.Remote;
public class RemoteMessageService
{
    private readonly ISignalRService _signalRService;
    private GrpcOptions _option;
    
    public RemoteMessageService(ISignalRService service)
    {
        _signalRService = service;
      
    }
    public void Run()
    {
        _option = App.GetOptions<GrpcOptions>();
        Task.Run(async () =>
        {
            while (true)
            {
                try
                {
                    if (!_signalRService.IsConnected)
                    {
                        await ConnectSignalR();
                    }
                }
                catch (Exception ex)
                {
                    throw Oops.Oh(ex.Message);
                }
                await Task.Delay(5000);
            }
        });
    }

    /// <summary>
    /// 连接SignalR
    /// </summary>
    /// <returns></returns>
    private async Task<bool> ConnectSignalR()
    {
        var result = await _signalRService.ConnectServer(_option.GrpcApiUrl, new GeneralCommon.Models.SignalR.User
        {
            ID = Guid.NewGuid().ToString(),
            Name = "EcsWeb",
            Type = GeneralCommon.Enums.DeviceEnum.BS
        });
        _signalRService.RemoteLogEvent -= SignalRService_RemoteLogEvent;
        _signalRService.RemoteLogEvent += SignalRService_RemoteLogEvent;
        _signalRService.MessageEvent -= SignalRService_MessageEvent;
        _signalRService.MessageEvent += SignalRService_MessageEvent;

        _signalRService.ClosedEvent -= _signalRService_ClosedEvent;
        _signalRService.ClosedEvent += _signalRService_ClosedEvent;

        _signalRService.ConnectedEvent -= _signalRService_ConnectedEvent;
        _signalRService.ConnectedEvent += _signalRService_ConnectedEvent;

        _signalRService.ListenRemoteLog();
        _signalRService.ListenMessage();

        return result;
    }
    // 监听消息
    private async void SignalRService_MessageEvent(object? sender, InformModel e)
    {
        if (OnlineUserHub._onlineUserHubContext == null) return;
        await OnlineUserHub._onlineUserHubContext.Clients.All.ReceiveRemoteInform(e);
        return;
       
    }

    private async void SignalRService_RemoteLogEvent(object? sender, RemoteLog e)
    {
        if (OnlineUserHub._onlineUserHubContext == null) return;
       await OnlineUserHub._onlineUserHubContext.Clients.All.ReceiveRemoteMessage(e);
        return;
    }



    private void _signalRService_ConnectedEvent(object? sender, string e)
    {
      
    }

    private void _signalRService_ClosedEvent(object? sender, string e)
    {
       
    }
}
